//
//  AppPlistController.m
//  AppManagement
//
//  Created by 珍 on 16/5/16.
//  Copyright © 2016年 abb.is.dev.eas. All rights reserved.
//

#import "AppPlistController.h"
#import "APPPlistView.h"
#import "MEAPPManager.h"
#import "SSZipArchive.h"
#import "Utils.h"
#import "CordovaViewController.h"
#import "NSArray+Log.h"


#import "ReimbursementSQL.h"
@interface AppPlistController ()<APPPlistViewDelegate>
{
    NSInteger downloadcount;
    CGFloat APPWith;
    
}


@property (nonatomic, strong) NSMutableArray *appPlistArray;
@property (nonatomic, strong) UIScrollView *appScrollView;

@property (nonatomic, assign) BOOL btnClick;
@property (nonatomic, strong) NSMutableArray *installArray;// 已安装
@property (nonatomic, strong) NSMutableArray *uninstallArray;// 未安装

@property (nonatomic, strong) NSString *unzippath;

@property (nonatomic, assign) BOOL isTip;//判断是否已经提示过安装
@property (nonatomic, assign) NSInteger installingAppCount;// 记录正在下载的APP数量



@end

@implementation AppPlistController
-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    

    [_appScrollView setContentOffset:CGPointMake(0, -64) animated:YES];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setNavigationBarItem];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#dcdcdc"];
     [self setupNavigationBarWithTitle:@"应用管理"];
    
    _appPlistArray = [[NSMutableArray alloc]init];
    
    _installArray  = [[NSMutableArray alloc]init];
    
    _uninstallArray = [[NSMutableArray alloc]init];
    NSLog(@"--%@",[Utils getDocumentPath]);
   
    [self setUI];
    [self requestAPPPlist];
    
  
}

- (void)setUI{

    _appScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT)];
    
    _appScrollView.userInteractionEnabled = YES;
    
    _appScrollView.showsHorizontalScrollIndicator = NO;
        [self.view addSubview:_appScrollView];

}
// 展示已经安装的应用
- (void)buildInstallApp{
    
     [_appScrollView removeAllSubviews];
    
     [self dealInstallAPPData];
    // 定义水平和垂直间距
    int marginX = 1;
    int marginY = 1;
    int totalCols = 3; // 每一行多少个小方格
    
    APPWith = (IPHONE_WIDTH - 2)/totalCols;   // 定义小方格的宽度
    int height = APPWith; // 定义小方格的高度
    
    CGFloat istallBottom = 10;

    for (int i = 0; i < _installArray.count; i++) {
        // 拿到当前应该使用的数据
        MEAPPManager *app = _installArray[i];
        
        int row = i / totalCols;
        int col = i % totalCols;
        int left = col * APPWith + (col + 1) * marginX;
        int top = row * APPWith + (row + 1) * marginY ;
        
        // 创建 CZAppView 对象
        CGRect frame = CGRectMake(left, top, APPWith, height);
        APPPlistView *appView = [APPPlistView appViewWithApp:app for:frame];
        [appView removeProgressBar];
        appView.imageBtn.tag = app.appId;
        // 加到 self.view 中
        [_appScrollView addSubview:appView];
        
        
        
        appView.delegate = self;
    }
    
    
    istallBottom = (_installArray.count +1) /totalCols *height;
    [_appScrollView setContentSize:CGSizeMake(IPHONE_WIDTH, istallBottom + 40)];


}



- (void)requestAPPPlist{
    
    [UIHelper showIndicatorToView:self.view];
    [AFNHttpRequest afnHttpRequestUrl:KAPPList param:nil success:^(id responseObject) {
        [UIHelper hideHUDForView:self.view];
        
        _appPlistArray = [MEAPPManager mj_objectArrayWithKeyValuesArray:responseObject[@"dataList"]];
        [self buildInstallApp];
        [self aleartInstallApp];
        
        
    } failure:^(NSError *error) {
        [UIHelper hideHUDForView:self.view];
        
    }];

}

#pragma mark -处理判断已安装或未安装数据
- (void)dealInstallAPPData{
    [_uninstallArray removeAllObjects];
    [_installArray removeAllObjects];
    // 从数据库获取
    NSMutableArray *tempArray =[NSMutableArray arrayWithArray:[[ReimbursementSQL sharedInstance] selectAppPlistSQLtable]];
    NSLog(@"---->%lu",(unsigned long)tempArray.count);
    
    for (MEAPPManager *model in _appPlistArray) {
        
            [_uninstallArray addObject:model];
            
            for (MEAPPManager *appSql in tempArray) {
                
                if (appSql.appId == model.appId) {
                    // 判断版本是否最新
                    if ([appSql.version isEqualToString: model.version]) {
                        
                        model.isNew = YES;
                    }else{
                        model.isNew = NO;
                        
                    }
                    
                    [_installArray addObject:model];
                    
                    [_uninstallArray removeObject:model];
                    
                }
  
            }
    }
     downloadcount = _installArray.count;
    
    NSLog(@"未安装个数=%lu  ---已安装个数= %lu",(unsigned long)_uninstallArray.count,(unsigned long)_installArray.count);
}

#pragma mark 提示安装新应用

- (void)aleartInstallApp{
    // 判断是否已经提示过
    if (_isTip == YES) {
        return;
    }
    
    if (_uninstallArray.count > 0) {
        [UIHelper alertWithMsg:[NSString stringWithFormat:@"你有%lu 个新应用未安装 ,是否逐一安装新应用",(unsigned long)_uninstallArray.count] viewController:self confirmAction:^{
            
            //逐一安装新应用
            for (MEAPPManager *model in _uninstallArray) {
            
            [self downloadWithApp:model];
            
        };

        } cancelAction:^{
            
            _isTip = YES;
        }];
 
    }
}

#pragma mark APPPlistViewDelegate
- (void)aPPPlistView:(APPPlistView *)drawer button_click:(UIButton *)button{
    [self dealInstallAPPData];
    if (_btnClick == YES) {
        return;
    }

    for (MEAPPManager *model in _installArray) {
        
        if (button.tag == model.appId) {
                
                // 判断版本是否最新
            
            if (model.isNew == YES) {
                
                _btnClick = NO;
                
                NSString *path = [NSString stringWithFormat:@"%@/%ld",[Utils getDocumentPath],(long)model.appId];
                
                NSLog(@"path==--%@",path);
                
                [Utils copyFolderToPath:[NSString stringWithFormat:@"%@/www",path] SuccessAction:^{
                    
                    CordovaViewController *VC = [[CordovaViewController alloc]init];
                    
                    NSString *htmlstr = [NSString stringWithFormat:@"%@/www/index.html?pctype=phone",path];
                    
                    NSLog(@"htmlstr-----%@",htmlstr);
                    
                    VC.urlString = htmlstr;
                    [self presentViewController:VC animated:YES completion:^{
                       }];
                        
                   
                }];
                    
                    
                
            }else{
                
                _btnClick = NO;
                
                //重新下载
                
                [self downloadWithApp:model];
                
                return;
                    
                }
            
        }
    }

}


// 添加未安装的app
- (APPPlistView *)addUninstallApp:(MEAPPManager *)app{
    
    // 定义水平和垂直间距
    int marginX = 1;
    
    int marginY = 1;
    int totalCols = 3; // 每一行多少个小方格
    
    int width = (IPHONE_WIDTH - 2)/totalCols;   // 定义小方格的宽度
    int height = width; // 定义小方格的高度
    
    
    NSInteger row = downloadcount / totalCols;
    NSInteger col = downloadcount% totalCols;
    int left = col * APPWith + (col + 1) * marginX;
    int top = row * APPWith + (row + 1) * marginY ;
        
    // 创建 CZAppView 对象
   CGRect frame = CGRectMake(left, top, width, height);
    APPPlistView *appView = [APPPlistView appViewWithApp:app for:frame];
    appView.imageBtn.tag = app.appId;
    // 加到 self.view 中
    [_appScrollView addSubview:appView];
        
    appView.delegate = self;
 
    [_appScrollView setContentSize:CGSizeMake(IPHONE_WIDTH,(_installArray.count +1) /totalCols *height)];
    return appView ;

}

-(void)downloadWithApp:(MEAPPManager *)app

{
    
    if (!app.ipaUrl) {
        return;
    }
    
    APPPlistView *appViews = [self addUninstallApp:app];
    [self initRoundedSlimProgress:appViews.progressBar];
    downloadcount ++;
    _installingAppCount++;

    
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];

    NSURL *url = [NSURL URLWithString:app.ipaUrl];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [[manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
       
        appViews.progressBar.hidden = NO;
        
        CGFloat precent = 1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount;

        NSLog(@"%f",1.0 *downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
        [appViews.progressBar setProgress:precent animated:NO];
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {

        
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        
        return [NSURL fileURLWithPath:fullPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        [appViews removeProgressBar];
        
        NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:response.suggestedFilename];
        if (!error) {
            //解压
            NSString *fileName = [NSString stringWithFormat:@"%ld",(long)app.appId];
            _unzippath = [[Utils getDocumentPath] stringByAppendingPathComponent:fileName];
            NSLog(@"  成功解压地址--->%@", _unzippath);
            [SSZipArchive unzipFileAtPath:fullPath toDestination:_unzippath];
            // 删除zip
            NSFileManager *fileManager=[NSFileManager defaultManager];
            
            [fileManager removeItemAtPath:fullPath error:nil];
            
            // 存入数据库
            
            [[ReimbursementSQL sharedInstance]insertAppPlistSQL:app];
            [_installArray addObject:app];
            [_uninstallArray removeObject:app];
            
            [_appScrollView setContentSize:CGSizeMake(IPHONE_WIDTH,(_installArray.count +1) /3 *APPWith)];
            
            _installingAppCount--;
            // 全部下载完毕后更新UI
            if (_installingAppCount == 0) {
                [self refreshUI];
            }
        }
        if (error) {
            NSLog(@"---->%@",error);
            [appViews removeFromSuperview];
            downloadcount--;
            [_appScrollView setContentSize:CGSizeMake(IPHONE_WIDTH,(_installArray.count +1) /3 *APPWith)];
            
            _installingAppCount--;
            if (_installingAppCount == 0) {
                [self refreshUI];
            }

        }
        
        
    }]resume];
}

- (void)initRoundedSlimProgress:(YLProgressBar *)progressBarRoundedSlim

{
    progressBarRoundedSlim.progressTintColor        = [UIColor colorWithRed:239/255.0f green:225/255.0f blue:13/255.0f alpha:1.0f];
    progressBarRoundedSlim.indicatorTextDisplayMode = YLProgressBarIndicatorTextDisplayModeTrack;
    progressBarRoundedSlim.stripesColor             = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.36f];
}



- (void)refreshUI
{

    [self.view.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    [self setUI];
    [self buildInstallApp];
    [_appScrollView setContentOffset:CGPointMake(0, -64) animated:YES];
}
@end
